package cn.wubo.vrr.help.schedule;

import cn.wubo.vrr.help.controller.IndexController;
import cn.wubo.vrr.help.entity.AttendanceResult;
import cn.wubo.vrr.help.entity.Person;
import cn.wubo.vrr.help.service.AttendanceResultService;
import cn.wubo.vrr.help.service.PersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@Component
public class ECPAttendance {
    private final static Logger logger = LoggerFactory.getLogger(ECPAttendance.class);

    @Autowired
    PersonService personService;
    @Autowired
    AttendanceResultService attendanceResultService;

    //@Scheduled(cron = "0 30 7 * * ?")
    public void onWork() {
        List<Person> personList = personService.findAll();
        for (Person p : personList) {
            /*AttendanceResult ar = new AttendanceResult();
            ar.setName(p.getName());
            try {
                ar.setRes(attendance(p, "1"));
            } catch (Exception e) {
                e.printStackTrace();
                ar.setRes(e.getMessage());
            }
            attendanceResultService.save(ar);*/
            ThreadAh ah = new ThreadAh(p, "1");
            ah.start();
        }
    }

    //@Scheduled(cron = "0 0 17 * * ?")
    //@Scheduled(cron="0/10 * * * * ?")
    public void outWork() {
        List<Person> personList = personService.findAll();
        for (Person p : personList) {
            /*AttendanceResult ar = new AttendanceResult();
            ar.setName(p.getName());
            try {
                ar.setRes(attendance(p, "2"));
            } catch (Exception e) {
                e.printStackTrace();
                ar.setRes(e.getMessage());
            }
            attendanceResultService.save(ar);*/
            ThreadAh ah = new ThreadAh(p, "2");
            ah.start();
        }
    }

    class ThreadAh extends Thread {
        private Person p;
        private String attState;

        public ThreadAh(Person p, String attState) {
            this.p = p;
            this.attState = attState;
        }

        @Override
        public void run() {
            int count = (int) (1 + Math.random() * 20);
            try {
                sleep(count * 1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            AttendanceResult ar = new AttendanceResult();
            ar.setName(p.getName());
            try {
                ar.setRes(attendance(p, attState));
            } catch (Exception e) {
                e.printStackTrace();
                ar.setRes(e.getMessage());
            }
            attendanceResultService.save(ar);
        }
    }

    private static String attendance(Person p, String attState) throws Exception {
        URL url = new URL("http://qmkqapp.qm.cn:9008/attendance/punch");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置连接输出流为true,默认false (post请求是以流的方式隐式的传递参数)
        conn.setDoOutput(true);
        // 设置连接输入流为true
        conn.setDoInput(true);
        // 设置请求方式为post
        conn.setRequestMethod("POST");
        // post请求缓存设为false
        conn.setUseCaches(false);
        // 设置该HttpURLConnection实例是否自动执行重定向
        conn.setInstanceFollowRedirects(true);

        // 设置内容的类型,设置为经过urlEncoded编码过的from参数
        conn.setRequestProperty("Host", "qmkqapp.qm.cn:9008");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Content-Length", "282");
        conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        conn.setRequestProperty("Origin", "file://");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 28; Android SDK built for x86 Build/NYC; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0  /QMWebBrowse(294)/cn.qm.mobile.ecp.qm");
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        conn.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.9");
        conn.setRequestProperty("X-Requested-With", "cn.qm.mobile.ecp.qm");

        // 建立连接
        // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
        conn.connect();

        // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
        OutputStream os = conn.getOutputStream();
        // 将参数输出到连接
        //125.43448183547137
        //43.796005929310134
        String str = "{\"imagePath\":\"\",\"attState\":" + attState + ",\"userName\":\"" + p.getName() + "\",\"pin\":\"" + p.getEmployeeId() + "\",\"departmentName\":\"软件研发服务中心\",\"longitude\":125.4344818354713" + ((int) (1 + Math.random() * 9)) + ",\"latitude\":43.79600592931013" + ((int) (1 + Math.random() * 9)) + ",\"locationName\":\"长春市启明软件园\",\"picturePath\":\"\",\"phone\":\"" + p.getPhone() + "\",\"email\":\"" + p.getEmail() + "\"}";
        logger.info(str);
        os.write(str.getBytes("UTF-8"));//注意编码和Content-Type保持一致
        os.flush();

        //输出连接信息，实际使用时去掉
        //outConnInfo(conn, url);

        // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
        BufferedReader dataIn = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        // 用来存储响应数据
        StringBuilder sb = new StringBuilder();
        // 循环读取流
        while ((line = dataIn.readLine()) != null) {
            sb.append(line).append(System.getProperty("line.separator"));
        }
        logger.info(sb.toString());
        return sb.toString();
    }
}
